import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_first_project/api/user.dart';
import 'package:flutter_first_project/utils/Emitter.dart';
import 'package:flutter_first_project/utils/toast.dart';
import 'package:image_picker/image_picker.dart';

class ProfilePage extends StatefulWidget {
  const ProfilePage({super.key,required this.userInfo});
  final Map<String, dynamic> userInfo;
  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
final TextEditingController _nickNameController = TextEditingController();

// 封装获取头像方法
Widget _getAvatar() {
  if(widget.userInfo['avatar'] != null && widget.userInfo['avatar'] != ''){
    return Image.network(
      widget.userInfo['avatar'],
      width: 30,
      height: 30,
    );
  }
  else{
    return Image.asset(
      'assets/images/avatar_1.jpg',
      width: 30,
      height: 30,
    );
  }
}
// 封装获取昵称方法
@override
  void initState() {
    // TODO: implement initState
    super.initState();
    if(widget.userInfo['nickName'] != null && widget.userInfo['nickName'] != ''){
      _nickNameController.text = widget.userInfo['nickName'];
    }
  }
  bool saving = false;
  String fileName = '';
  bool isSelectPhoto = false;
  //保存用户信息
  void _saveUserInfo() async {
    if(_nickNameController.text.isEmpty){
      PrompAction.showFales('昵称不能为空');
      return;
    }
    RegExp reg  = RegExp(r'^[\u4e00-\u9fa5a-zA-Z0-9_]{2,18}$');
    if(!reg.hasMatch(_nickNameController.text)){
      PrompAction.showFales('昵称格式不正确');
      return;
    }

  if(!saving){
    saving = true;
    if(isSelectPhoto){
      // 说明需要上传
      // 区分web ios android，鸿蒙
      if(kIsWeb){
        // 网页端上传
        // 将本地的bolob数据转为二进制上传文件
        FormData data = FormData.fromMap({
          'file': MultipartFile.fromBytes(
            await XFile(widget.userInfo['avatar']).readAsBytes(), //二进制
            filename: fileName, //文件名
            contentType: DioMediaType('image','png')),
            'type':'avatar'
        });
// 将本地路径转换为二进制
        var res = await uploadPhotoAPI(data);
        setState(() {
          widget.userInfo['avatar'] = res['url'];
        });
        isSelectPhoto = false;
        fileName = '';
      }
    }
  }

     //保存昵称
     await updateUserInfoAPI({
      'nickName': _nickNameController.text,
      'avatar': widget.userInfo['avatar']
     }
     );
    PrompAction.showSuccess('修改昵称成功');
    eventBus.fire(LogSuccessEvent()); //不用返回因为可能只修改了头像
  }

// 选择头像
void _selectPhoto() async {
  ImagePicker  picker = ImagePicker(); //创建图片选择器
  XFile? file = await picker.pickImage(source: ImageSource.gallery); // 从相册选择图片
  if (file != null) {
   setState(() {
      widget.userInfo['avatar'] = file.path; //将选择的图片路径保存到userInfo中
   });
    PrompAction.showSuccess('选择头像成功');
    // 返回上一页
    Navigator.pop(context);
  }
}


   // 显示选择头像弹层
  void _showAvatarDialog() {
    showModalBottomSheet(
        context: context,
        builder: (context) {
          return SizedBox(
            width: double.infinity,
            height: 180,
            child: Column(
              children: [
                Container(
                  alignment: Alignment.center,
                  height: 60,
                  decoration: const BoxDecoration(
                      border: Border(
                          bottom: BorderSide(width: 0.5, color: Colors.grey))),
                  child: const Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(Icons.camera_alt),
                      SizedBox(
                        width: 10,
                      ),
                      Text(
                        "拍照",
                        style: TextStyle(fontSize: 20),
                      )
                    ],
                  ),
                ),
                Container(
                  alignment: Alignment.center,
                  height: 60,
                  decoration: const BoxDecoration(
                      border: Border(
                          bottom: BorderSide(width: 0.5, color: Colors.grey))),
                  child:  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      const Icon(Icons.photo_album),
                      const SizedBox(
                        width: 10,
                      ),
                      GestureDetector(
                        onTap: () {
                          _selectPhoto();
                        },
                        child: const Text(
                        "相册",
                        style: TextStyle(fontSize: 20),
                      )
                      ),
                      
                    ],
                  ),
                ),
                Container(
                  alignment: Alignment.center,
                  height: 60,
                  child: GestureDetector(
                    onTap: () {
                      Navigator.pop(context);
                    },
                    child: const Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(Icons.cancel_outlined),
                        SizedBox(
                          width: 10,
                        ),
                        Text(
                          "取消",
                          style: TextStyle(fontSize: 20),
                        )
                      ],
                    ),
                  ),
                )
              ],
            ),
          );
        });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('个人信息'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: ListView(
        padding: const EdgeInsets.all(10),
        children: [
          SizedBox(
            height: 40,
            child: Row(
              children: [
                const Text(
                  '头像',
                  style: TextStyle(fontSize: 16),
                ),
                const Spacer(),
                Row(
                  children: [
                    GestureDetector(
                      onTap: () {
                        _showAvatarDialog();
                      },
                      child:  ClipRRect(
                      borderRadius: BorderRadius.circular(50.0),
                      child: _getAvatar(),
                    ),
                    ),
                    const Icon(Icons.arrow_forward_ios, size: 12)
                  ],
                )
              ],
            ),
          ),
           Row(
            children: [
              const Text('昵称'),
              const Spacer(),
              Expanded(
                child: TextField(
                  controller: _nickNameController,
                  decoration: const InputDecoration(
                    hintText: '请输入昵称',
                    border: InputBorder.none,
                  ),
                  textAlign: TextAlign.right,
                ),
              ),
              const Icon(Icons.arrow_forward_ios, size: 12)
            ],
          ),
          const SizedBox(
            height: 20,
          ),
          Row(
            children: [
              Expanded(
                child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color.fromARGB(255, 85, 145, 175),
                    minimumSize: const Size(100, 50),
                  ),
                  onPressed: () {
                    _saveUserInfo();
                  },
                  child: const Text(
                    '保存',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 20,
                    ),
                  ),
                ),
              )
            ],
          )
        ],
      ),
    );
  }
}
